<template>
  <el-dialog
    custom-class="set-live-comp"
    :title="title"
    :close-on-click-modal="false"
    :visible="visible"
    :width="$setRem(500)"
    :before-close="handleCancel">
    <el-form
      class="set-live-form"
      size="medium"
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      :label-width="$setRem(120)"
    >
      <el-row>
        <el-col :span="22">
          <el-form-item label="通道号" prop="channelNo" required>
            <el-cascader
              popper-class="camera-cascader"
              clearable
              :props="{
                value: 'deviceId',
                label: 'name',
                children: 'channelList',
              }"
              :options="channelList"
              v-model="ruleForm.channelNo"
              :show-all-levels="false">
            </el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item label="摄像头名称" prop="cameraName" required>
            <el-input placeholder="请输入摄像头名称" v-model="ruleForm.cameraName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item label="摄像头类型" prop="cameraType" required>
            <el-input placeholder="请输入摄像头类型" v-model="ruleForm.cameraType"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item label="标签类型" prop="labelType" required>
            <el-select v-model="ruleForm.labelType">
              <el-option value="1" label="图片">图片</el-option>
              <el-option value="2" label="地图">地图</el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item label="位置" prop="location" required>
            <location
              v-if="ruleForm.labelType === '2'"
              v-model="ruleForm.location"
              :hasAltitude="false">
            </location>
            <picture-mark v-else v-model="ruleForm.location"></picture-mark>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span class="dialog-footer">
      <el-button type="primary" @click="handleCancel">取 消</el-button>
      <el-button
        class="success"
        type="primary"
        :loading="loading"
        @click="hanldeSave">
        保 存
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import location from '@/components/project/surveillance/location';
import PictureMark from '@/components/project/surveillance/PictureMark';

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({})
    },
    projectId: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      channelList: [],
      ruleForm: {
        id: '',
        cameraName: '',
        cameraType: '',
        channelNo: [],
        labelType: '1',
        location: {
          lng: '',
          lat: '',
          x: '',
          y: '',
          altitude: '',
        }
      },
      // form 表单校验规则
      rules: {
        cameraName: [
          { required: true, message: '请输入摄像头名称' }
        ],
        cameraType: [
          { required: true, message: '请输入摄像头类型' }
        ],
        channelNo: [
          { required: true, message: '请输入通道号' }
        ],
        location: [
          { required: true, message: '请完善位置信息' },
          { validator: this.locationValidator, trigger: 'blur' }
        ],
      },
    };
  },
  computed: {
    title() {
      return `${this.type === 'add' ? '新增' : '编辑'}视频监控`;
    },
    currentDevice() {
      if (!this.ruleForm.channelNo) return null;
      const [deviceSerial, channelNo] = this.ruleForm.channelNo;
      for (const item of this.channelList) {
        if (item.deviceSerial === deviceSerial) {
          return item.channelList.find(v => v.channelNo === channelNo);
        }
      }
      return null;
    }
  },
  watch: {
    formData: {
      deep: true,
      handler: function (data) {
        if (this.$checkType(data) !== 'object') return;
        const { deviceSerial, channelNo, pointPosition } = data;
        Object.keys(data).length && Object.keys(this.ruleForm).forEach(key => {
          const value = data[key];
          if (key === 'channelNo') {
            const channels = [];
            deviceSerial && channels.push(deviceSerial);
            (channelNo || channelNo === 0) && channels.push(channelNo);
            this.ruleForm[key] = channels;
            return;
          }
          if (key === 'location') {
            let location = {};
            try {
              if (pointPosition) location = JSON.parse(pointPosition);
            } catch (e) {}
            this.ruleForm[key] = location;
            return;
          }
          if (key === 'labelType') {
            this.ruleForm[key] = value || '1';
            return;
          }
          this.ruleForm[key] = value || '';
        });
      }
    },
    visible(val) {
      if (val) {
        this.getCameraListAll();
        return;
      }
      this.ruleForm = {
        id: '',
        cameraName: '',
        cameraType: '',
        channelNo: [],
        labelType: '1',
        location: {
          lng: '',
          lat: '',
          x: '',
          y: '',
        }
      };
    },
    'ruleForm.channelNo'(val) {
      if (val) {
        if (this.currentDevice) {
          const { channelName, deviceName } = this.currentDevice;
          this.ruleForm.cameraName = channelName || deviceName;
        }
        return;
      }
      this.ruleForm.cameraName = '';
    }
  },
  components: {
    location,
    PictureMark,
  },
  methods: {
    async getCameraListAll() {
      const { success, data: {
        data
      }} = await this.$Model.getCameraListAll({
        pageSize: 50,
        pageStart: 1,
        projectId: this.projectId,
      });
      if (success && data) {
        const list = data.list || [];
        this.channelList = list.map(v => {
          const { lappCameraList } = v;
          let channelList = [];
          if (lappCameraList && lappCameraList.length) {
            channelList = lappCameraList.map(item => ({
              ...item,
              name: `${item.channelName} (${item.channelNo})`,
              deviceId: item.channelNo
            }));
          }
          return {
            ...v,
            deviceId: v.deviceSerial,
            name: v.deviceName,
            channelList,
          };
        });
      }
    },
    /**
     * 校验位置信息
     * @param rule 校验规则
     * @param value 位置数据
     * @param callback 校验回调
     */
    locationValidator(rule, value, callback) {
      const check = Object.keys(this.ruleForm.location).some(key => {
        return !value[key] || /^\s+$/.test(value[key]);
      });
      if (check) return callback('请完善位置信息');
      return callback();
    },
    // 保存
    hanldeSave() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$emit('save', this.ruleForm);
        }
      });
    },
    // 取消
    handleCancel() {
      this.$emit('cancel', false);
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/dialog';
  .set-live-comp {
    .set-live-form {
      width: 100%;
      padding-right: 30px;
      .el-cascader {
        width: 100%;
      }
    }
    .dialog-footer {
      display: flex;
      justify-content: center;
      margin: 10px 0;
    }
  }
</style>
